
/**
 * @desc      扁平数组转树状结构
 * @example :[{id:0,name:xx},{id:01,pid:0,name:xx}]
 * @returns :[{id:0,name:xx,children:[{id:01,name:xx},{id:02,name:xx}]}]
 */

const arrayToTree = (arr,id='id',pid='pid',children='children') =>{
  // 深拷贝
  const data =  JSON.parse(JSON.stringify(arr));
  const  result = []
  const  hash = {}
  data.forEach((item, index) => {
      // 生成一个以为id为数组下标的数组
      hash[data[index][id]] = data[index] // 方便一对一查找
  })

  // 如果有pid则是子节点。没有pid即是一级节点
 data.forEach((item) => {
      item.key = item.id
      item.title = item.name
      const hashVP = hash[item[pid]]
      if (hashVP) {
          !hashVP[children] && (hashVP[children] = [])
          hashVP[children].push(item)
      }
      else if(!hashVP){
        result.push(item)
      }
  })
  return result;
}

/**
 * @desc      根据生成的树状结构生成对应的扁平数据
 * @example :[{key:0,title:xx,children:[{key:01,title:xx},{key:02,title:xx}]}]
 * @returns :[{key:0,title:xx},{key:01,title:0}]
 */


const generateList = (data) => {
  const arr = [];
  for (let i = 0; i < data.length; i+1) {
    const node = data[i];
    const {key,title} = node;
    arr.push({ key, title });
    if (node.children) {
      generateList(node.children, node.key);
    }
  }
  return arr;
};


/**
 * @desc      点击该节点获取其以上的节点
 * @example :
 * @returns :
 */

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i+1) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

const addParams = (list) => {
  list.forEach(item=>{
    item.key = item.id;
    item.title = item.name;
  })
  return list;
};

export  {
  arrayToTree,
  generateList,
  getParentKey,
  addParams,
}
